﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace Transport
{
    class Server
    {
        private TcpListener listener;
        private TcpClient client;
        private Thread trListener;
        private bool serverRun;
        private IPAddress ip;
        private int port;
        public static event StatusChangedEventHandler StatusChanged;
        private static StatusChangedEventArgs e;
        // This delegate is needed to specify the parameters we're passing with our event
        public delegate void StatusChangedEventHandler(object sender, StatusChangedEventArgs e);

        // The constructor sets the IP ip to the one retrieved by the instantiating object
        public Server(IPAddress ip, int port)
        {
            this.ip = ip;
            this.port = port;
        }
        public void StartListening()
        {
            listener = new TcpListener(ip, port);
            listener.Start();
            serverRun = true;
            trListener = new Thread(KeepListening);
            trListener.Start();
        }

        private void KeepListening()
        {
            while (serverRun)
            {
                client = listener.AcceptTcpClient();
                Connection newConnection = new Connection(client);
            }

        
        }

        public static void SendMessage(string message)
        {
            // First of all, show in our application who says what
            e = new StatusChangedEventArgs(message);
            OnStatusChanged(e);
        }

        // This is called when we want to raise the StatusChanged event
        public static void OnStatusChanged(StatusChangedEventArgs e)
        {
            StatusChangedEventHandler statusHandler = StatusChanged;
            if (statusHandler != null)
            {
                // Invoke the delegate
                statusHandler(null, e);
            }
        }
    }
}
